<?php
/**
 * Created by PhpStorm.
 * User: jianqi
 * Date: 2017/8/10
 * Time: 10:46
 */

use think\Request;
use think\Db;
use Wechat\Loader;

//操作日志

function sys_log($uid, $aid = "", $title = "", $desc = "")
{

    $data['uid'] = $uid;
    $data['aid'] = $aid;
    $data['title'] = $title;
    $data['desc'] = $desc;
    $data['addtime'] = date("Y-m-d H:i:s");
    Db::table('sys_actlog')->insert($data);


}




//根据A查询B
function idtoval($table, $where, $key)
{

    return Db::table($table)->where($where)->value($key);
}

function & load_wechat($type = '')
{
    static $wechat = array();
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        $config = Db::table('wechat_config')->find(10000);
        $config['cachepath'] = CACHE_PATH . 'Data/';
        $wechat[$index] = Loader::get($type, $config);
    }
    return $wechat[$index];
}

//根据A查询array
function idtoarray($table, $where)
{

    return Db::table($table)->where($where)->find();
}


function jq()
{

    return '<script type="text/javascript" src="' . _STATIC . '/js/jquery-2.2.4.min.js"></script>';


}


function ico(){


    return '<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">';

}



//加载layer

function layer()
{


    return '<script type="text/javascript" src="' . _STATIC . '/layer/layer.js"></script>';


}

//加载echart

function echart()
{


    return '<script type="text/javascript" src="' . _STATIC . '/js/echarts.min.js' . '"></script>';


}


//加载layui
function layui()
{

    return '<script type="text/javascript" src="' . _STATIC . '/layui/layui.all.js' . '"></script>
             <link rel="stylesheet" href="' . _STATIC . '/layui/css/layui.css" media="all" />   
                  ';

}


//加载layui
function ue()
{

    return '<script type="text/javascript" src="' . _STATIC . '/ueditor/ueditor.config.js' . '"></script>
             <script type="text/javascript" src="' . _STATIC . '/ueditor/ueditor.all.js' . '"></script>
             
                
                  ';

}


//加载省市县

function citys()
{


    return '<script type="text/javascript" src="' . _STATIC . '/js/citys.js' . '"></script>';


}



//判断是否ajax请求
function IS_AJAX()
{

    return $a = (Request::instance()->isAjax()) ? 1 : 0;

}


//微信登录
function getwxinfo($url=0){
     
     if($url==0){
       session('burl','http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);

     }else{
     
      session('burl',$url);

     }

   
    $oauth = & load_wechat('Oauth');
    $result = $oauth->getOauthRedirect(Url('api/oauth/getwxinfo','','',true), '1', 'snsapi_userinfo');


    header('Location: '.$result);


}

//导出excel

/**
 * 导出数据为excel表格
 *@param $data    一个二维数组,结构如同从数据库查出来的数组
 *@param $title   excel的第一行标题,一个数组,如果为空则没有标题
 *@param $filename 下载的文件名
 *@examlpe
//$stu = M ('User');
// $arr = $stu -> select();
// exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
 **/
function exportexcel($data = array() , $title = array() , $filename = 'report') {
    header("Content-type:application/octet-stream");
    header("Accept-Ranges:bytes");
    header("Content-type:application/vnd.ms-excel");
    header("Content-Disposition:attachment;filename=" . $filename . ".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    //导出xls 开始
    if (!empty($title)) {
        foreach ($title as $k => $v) {
            $title[$k] = iconv("UTF-8", "GB2312", $v);
        }
        $title = implode("\t", $title);
        echo "$title\n";
    }
    if (!empty($data)) {
        foreach ($data as $key => $val) {
            foreach ($val as $ck => $cv) {
                $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
            }
            $data[$key] = implode("\t", $data[$key]);
        }
        echo implode("\n", $data);
    }
}


//获取汉字首字母
function getfirst($str) {
    //获取字符串首字母
    if (empty($str)) {
        return '';
    }
    $fchar = ord($str{0});
    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= - 20319 && $asc <= - 20284) return 'A';
    if ($asc >= - 20283 && $asc <= - 19776) return 'B';
    if ($asc >= - 19775 && $asc <= - 19219) return 'C';
    if ($asc >= - 19218 && $asc <= - 18711) return 'D';
    if ($asc >= - 18710 && $asc <= - 18527) return 'E';
    if ($asc >= - 18526 && $asc <= - 18240) return 'F';
    if ($asc >= - 18239 && $asc <= - 17923) return 'G';
    if ($asc >= - 17922 && $asc <= - 17418) return 'H';
    if ($asc >= - 17417 && $asc <= - 16475) return 'J';
    if ($asc >= - 16474 && $asc <= - 16213) return 'K';
    if ($asc >= - 16212 && $asc <= - 15641) return 'L';
    if ($asc >= - 15640 && $asc <= - 15166) return 'M';
    if ($asc >= - 15165 && $asc <= - 14923) return 'N';
    if ($asc >= - 14922 && $asc <= - 14915) return 'O';
    if ($asc >= - 14914 && $asc <= - 14631) return 'P';
    if ($asc >= - 14630 && $asc <= - 14150) return 'Q';
    if ($asc >= - 14149 && $asc <= - 14091) return 'R';
    if ($asc >= - 14090 && $asc <= - 13319) return 'S';
    if ($asc >= - 13318 && $asc <= - 12839) return 'T';
    if ($asc >= - 12838 && $asc <= - 12557) return 'W';
    if ($asc >= - 12556 && $asc <= - 11848) return 'X';
    if ($asc >= - 11847 && $asc <= - 11056) return 'Y';
    if ($asc >= - 11055 && $asc <= - 10247) return 'Z';
    return null;
}


//递归用于循环分类
function digui($cate, $attrid, $html = '　|--', $pid = 0, $level = 0) {
    $arr = array();
    foreach ($cate as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level + 1;
            $v['html'] = str_repeat($html, $level);
            $arr[] = $v;
            $arr = array_merge($arr, digui($cate, $attrid, $html, $v[$attrid], $level + 1));
        }
    }
    return $arr;
}



//清空缓存
//使用方法
/*
public function cache(){
           $con=deldir('App/Runtime');
            if($con>0){
                成功
            }else{
                失败
            }
        }
*/
function deldir($dir)
{
    $dh = opendir($dir);
    while ($file = readdir($dh))
    {
        if ($file != "." && $file != "..")
        {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath))
            {
                unlink($fullpath);
            } else
            {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    if (rmdir($dir))
    {
        return true;
    } else
    {
        return false;
    }
}



// 马赛克
function msk($str,$start=-4,$over=5,$x='****'){

    return substr_replace($str,$x,$start,$over);


}



//短信包接口
function sendcms($user,$password,$tel,$content){


    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
    $smsapi = "http://api.smsbao.com/"; //短信网关
    $user = $user; //短信平台帐号
    $pass = md5($password); //短信平台密码
    $content=$content;//要发送的短信内容
    $phone = $tel;//要发送短信的手机号码
    $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
    $result =file_get_contents($sendurl) ;
    return $statusStr[$result];
}




/* $time 时间戳  $type 如果时间距现在大于30 天用什么格式显示*/
function timeToDay($time,$type="Y-m-d H:i") {

    $s=time()-$time;
    $val='';
    if($s<1){ $val="刚刚";}  //如果发布时间小于1秒
    if($s<60){$val=$s."秒前";}
    if($s>60 && $s<3600 ){$val=floor($s/60)."分钟前";}
    if($s>3600 && $s<3600*24){ $val=floor(($s/3600))."小时前";}

    //匹配昨天
    if($time<mktime(0,0,0,date('m'),date('d'),date('Y')) && $time> mktime(0,0,0,date('m'),date('d')-1,date('y'))){$val="昨天".date('H:i',$time);}


    //匹配30天内
    if($time<mktime(0,0,0,date('m'),date('d')-1,date('Y')) && $s<3600*24*30){

        $val=mktime(0,0,0,date('m'),date('d'),date('Y'))-mktime(0,0,0,date('m',$time),date('d',$time),date('Y',$time));

        $val=$val/(24*3600);
        $val=floor($val)."天前";
    }


    //如果大于30天
    if($s>3600*24*30){ $val=date($type,$time);}



    return $val;

}


//载入动画
function loading(){



    $val='<style>
#jqloading{z-index:2016001}.loading-modal,.loading-modal>i{position:absolute;width:10px;height:10px}.loading-modal{top:50%;left:50%;margin:-5px 0 0 -5px}.loading-modal>i{top:-8px;left:8px;display:block;background:#354d59;border-radius:10px;-webkit-animation:spin3 2s ease-in-out infinite}.loading-modal>i:first-child{top:8px;left:-8px;background:#eeb269;-webkit-animation:spin 2s ease-in-out infinite}.loading-modal>i:nth-child(2){top:8px;left:8px;background:#4db19e;-webkit-animation:spin2 2s ease-in-out infinite}.loading-modal>i:last-child{top:-8px;left:-8px;background:#dc5753;-webkit-animation:spin4 2s ease-in-out infinite}@-webkit-keyframes spin{0%,100%{top:8px;left:-8px;-webkit-transform:scale(1)}25%{top:-8px;left:-8px;-webkit-transform:scale(1)}50%{top:-8px;left:8px;-webkit-transform:scale(1)}75%{top:8px;left:8px;-webkit-transform:scale(1)}}@-webkit-keyframes spin2{0%,100%{top:8px;left:8px;-webkit-transform:scale(1)}25%{top:8px;left:-8px;-webkit-transform:scale(1)}50%{top:-8px;left:-8px;-webkit-transform:scale(1)}75%{top:-8px;left:8px;-webkit-transform:scale(1)}}@-webkit-keyframes spin3{0%,100%{top:-8px;left:8px;-webkit-transform:scale(1)}25%{top:8px;left:8px;-webkit-transform:scale(1)}50%{top:8px;left:-8px;-webkit-transform:scale(1)}75%{top:-8px;left:-8px;-webkit-transform:scale(1)}}@-webkit-keyframes spin4{0%,100%{top:-8px;left:-8px;-webkit-transform:scale(1)}25%{top:-8px;left:8px;-webkit-transform:scale(1)}50%{top:8px;left:8px;-webkit-transform:scale(1)}75%{top:8px;left:-8px;-webkit-transform:scale(1)}}
</style>
<div class="loading-modal" id="jqloading"><i></i><i></i><i></i><i></i></div>
 
   
 <script type="text/javascript">
    window.onload = function(){ 
       var dom = document.getElementById("jqloading");
            document.body.removeChild(dom)
　　  
　　}; 
</script>';
    return $val;



}



//移动端 触屏事件

function tap(){

    return "<script src='http://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js'></script>
<script type='text/javascript'>
if ('addEventListener' in document) {
    document.addEventListener('DOMContentLoaded', function() {
        FastClick.attach(document.body);
    }, false);}</script>";
}



function juhesms($tel,$msg){

    //【搜禾网】您的验证码为#code#，15分钟内有效
    header('content-type:text/html;charset=utf-8');

    $url = 'http://v.juhe.cn/sms/send'; //短信接口的URL
  
$params = array(
    'key'   => 'fd9bcd90dfa94305cb45be25eca7937d', //您申请的APPKEY
    'mobile'    => $tel, //接受短信的用户手机号码
    'tpl_id'    => '48635', //您申请的短信模板ID，根据实际情况修改
    'tpl_value' =>'#code#='.$msg //您设置的模板变量，根据实际情况修改
);



    $httpInfo = array();
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt( $ch , CURLOPT_POST , true );
    curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
    curl_setopt( $ch , CURLOPT_URL , $url );
    
    
    $response = curl_exec( $ch );
    if ($response === FALSE) {
        echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
    $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    

     $result = json_decode($response,true);
     $error_code = $result['error_code'];
     
     if($error_code == 0){
        //状态为0，说明短信发送成功

        $t= 200;
    }else{
        //状态非0，说明失败
        
        $t= "短信发送失败(".$error_code.")：".$msg;
    }

    
    return $t ;



}


function U($url){


  return url($url);

}



function get_page_url() { 
    $pageURL = 'http'; 
    if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";} 
    $pageURL .= "://"; 
    if ($_SERVER["SERVER_PORT"] != "80") { 
        $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; 
    } else { 
        $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
    } 
    return $pageURL; 
}

